#!/bin/bash
# 会说话的键盘启动脚本

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 设置环境变量避免X11错误
export QT_X11_NO_MITSHM=1
export _X11_NO_MITSHM=1
export _MESA_NO_ERROR=1

# 检查Python是否可用
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到Python3，请先安装Python3"
    read -p "按回车键退出..."
    exit 1
fi

# 检查依赖库
echo "🔍 检查依赖库..."
python3 -c "import pynput, pygame" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "❌ 缺少依赖库，正在自动安装..."
    echo "📦 安装 pynput 和 pygame..."
    
    # 尝试用户安装
    pip3 install --user pynput pygame 2>/dev/null
    if [ $? -ne 0 ]; then
        echo "⚠️ 用户安装失败，尝试系统安装..."
        sudo pip3 install pynput pygame
        if [ $? -ne 0 ]; then
            echo "❌ 依赖库安装失败！"
            echo ""
            echo "请手动运行以下命令安装依赖："
            echo "  pip3 install pynput pygame"
            echo "或者："
            echo "  sudo pip3 install pynput pygame"
            echo ""
            echo "如果仍有问题，请运行安装脚本："
            echo "  ./install_desktop.sh"
            echo ""
            read -p "按回车键退出..."
            exit 1
        fi
    fi
    echo "✅ 依赖库安装完成"
else
    echo "✅ 依赖库检查通过"
fi

# 启动程序
echo "启动会说话的键盘..."
python3 audio_speaking_keyboard.py

# 如果程序异常退出，显示错误信息
if [ $? -ne 0 ]; then
    echo "程序异常退出"
    read -p "按回车键退出..."
fi
